package com.tyqx.hashchainbiz.controller.jzt;

import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;
import com.tyqx.hashchainbean.module.HashChainStatistics;
import com.tyqx.hashchainbean.module.TrackUser;
import com.tyqx.hashchainbean.module.UseProduct;
import com.tyqx.hashchainbean.vo.ImageAttachementVO;
import com.tyqx.hashchainbean.vo.JZTGS1AttachmentVO;
import com.tyqx.hashchainbiz.controller.config.JwtTokenUtil;
import com.tyqx.hashchainbiz.controller.mongodb.MongoDBGridFSUtil;
import com.tyqx.hashchainbiz.service.JZTGS1AttachmentService;
import com.tyqx.hashchainbiz.service.MysqlDataBaseAndMongDbConfigService;
import com.tyqx.hashchainbiz.service.TrackUserService;
import hashchainutil.common.Dto;
import hashchainutil.common.DtoUtil;
import hashchainutil.common.EmptyUtils;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/JZTApi/GS1")
@CrossOrigin
public class JZTGS1AttachmentController {

    @Resource
    private MongoDatabase mongoDatabase;

    @Resource
    private TrackUserService trackUserService;

    @Resource
    private MysqlDataBaseAndMongDbConfigService mysqlDataBaseAndMongDbConfigService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private JZTGS1AttachmentService jztgs1AttachmentService;



    @RequestMapping(value = "/addGS1Attachment", method = RequestMethod.POST)
    @ResponseBody
    public Dto addGS1Attachment(HttpServletRequest request) throws Exception {

        String jwtToken = request.getHeader("Authorization");
        String tokenUserName = jwtTokenUtil.getUsernameFromToken(jwtToken);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("files");
        String ssccCode = request.getParameter("ssccCode");
        String userName=request.getParameter("userName");
        if (files.size() < 1) {
            return DtoUtil.returnFail("文件不能为空", "100001");
        }
        if (EmptyUtils.isEmpty(userName)) {
            return DtoUtil.returnFail("用户名不能为空", "100002");
        }
        if (EmptyUtils.isEmpty(ssccCode)) {
            return DtoUtil.returnFail("GS1条码不能为空", "100003");
        }
        TrackUser trackUser=trackUserService.getUserByCode(userName);
        if(EmptyUtils.isEmpty(trackUser)){
            String msg="用户找不到";
            return DtoUtil.returnFail(msg,"100006");
        }

        if(!tokenUserName.equals(userName)){
            String msg="用户名跟token用户名不匹配";
            return DtoUtil.returnFail(msg,"100005");
        }
        String msg = "";
        List<Integer> successList = new ArrayList<>();
        List<Integer> failList = new ArrayList<>();
        Map<String, Object> documentMap = new HashMap<>();
        documentMap.put("userName", userName);
        documentMap.put("ssccCode", ssccCode);


        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = sdf.parse(sdf.format(currentDate));
        Date updateTime = createTime;
        for (int i = 0; i < files.size(); i++) {

            System.out.println("current file index:" + i);
            try {
                documentMap.put("offset", i);
                InputStream inputStream = files.get(i).getInputStream();
                String contentType = files.get(i).getContentType();

                documentMap.put("contentType",contentType);
                String bucketName="jztGS1AttachmentList";
                GridFSBucket gridFSFilesBucket = GridFSBuckets.create(mongoDatabase,bucketName);
                /*MongoCollection<Document> mongoCollection=mongoDatabase.getCollection("jztAttachmentBusinessList");
                mongoCollection.createIndex(new Document("",""));*/
                GridFSUploadOptions options = new GridFSUploadOptions()
                        .chunkSizeBytes(261120)
                        .metadata(new Document("documentMap", documentMap));
                String fileName = "mongodb-jzt-GS1-attachment-0";

                double dataCount=files.get(i).getSize()/1000000.00;
                String dataType="jztGS1Attachment";
                HashChainStatistics hashChainStatistics=new HashChainStatistics();
                hashChainStatistics.setDataCount(dataCount);
                hashChainStatistics.setDataType(dataType);
                hashChainStatistics.setUserName(userName);
                hashChainStatistics.setCreateTime(createTime);
                hashChainStatistics.setUpdateTime(updateTime);
                /*Integer flag=hashChainStatisticsService.add(hashChainStatistics);
                if (flag == 0){
                    throw new Exception("record statistcs error");
                }
                ObjectId fileId = gridFSFilesBucket.uploadFromStream(fileName, inputStream, options);*/
                //ObjectId objectId=hashChainStatisticsService.insertDataCountAndMongoDBGridFS(hashChainStatistics,fileName,inputStream,options,gridFSFilesBucket);
                ObjectId objectId=mysqlDataBaseAndMongDbConfigService.insertDataCountAndMongoDBGridFS(hashChainStatistics,fileName,inputStream,options,gridFSFilesBucket);
                if (EmptyUtils.isEmpty(objectId)) {
                    failList.add(i);
                } else {
                    successList.add(i);
                }
            } catch (Exception e) {
                e.printStackTrace();
                failList.add(i);
            }
        }
        if (failList.size() == 0) {
            msg = "信息上链成功";
            return DtoUtil.returnSuccess(msg);
        } else if (successList.size() == 0) {
            msg = "信息上链失败";
            return DtoUtil.returnFail(msg, "100001");
        } else {
            msg = "success: " + successList.size() + ", fail: " + failList.size()+".\n Success list: " + successList.toString()+".\n Fail list: " + failList.toString();
            return DtoUtil.returnFail(msg, "100002");
        }

    }




    @RequestMapping(value = "/getJZTGS1AttachmentBySsccCode", method = RequestMethod.POST)
    @ResponseBody
    public Dto getJZTGS1AttachmentBySsccCode(@RequestParam(value = "ssccCode", required = true) String ssccCode,HttpServletRequest request) throws Exception {
        String jwtToken = request.getHeader("Authorization");
        String userName = jwtTokenUtil.getUsernameFromToken(jwtToken);
        List<JZTGS1AttachmentVO> jztgs1AttachmentVOList = jztgs1AttachmentService.grantGetJZTGS1AttachmentBySsccCode(ssccCode,userName);
        if (jztgs1AttachmentVOList.size() > 0) {
            return DtoUtil.returnSuccess("查询成功", jztgs1AttachmentVOList);
        } else {
            return DtoUtil.returnFail("未查询到记录", "10001");
        }
    }


    @RequestMapping(value = "/getAttachmentBySsccCode", method = RequestMethod.POST)
    @ResponseBody
    public Dto getAttachmentBySsccCode(@RequestParam(value = "ssccCode", required = true) String ssccCode,HttpServletRequest request) throws Exception {
        String jwtToken = request.getHeader("Authorization");
        String userName = jwtTokenUtil.getUsernameFromToken(jwtToken);
        List<JZTGS1AttachmentVO> jztgs1AttachmentVOList = jztgs1AttachmentService.grantGetJZTGS1AttachmentBySsccCode(ssccCode,userName);
        List<ImageAttachementVO> attachementVOList = new ArrayList<>();
        GridFSBucket gridFSFilesBucket = GridFSBuckets.create(mongoDatabase, "jztGS1AttachmentList");
        for (int i = 0; i < jztgs1AttachmentVOList.size(); i++) {
            String contentType="";
            String objectId = jztgs1AttachmentVOList.get(i).getObjectId();
            ImageAttachementVO imageAttachementVO = MongoDBGridFSUtil.getJZTAttachmentByObjectId(gridFSFilesBucket, new ObjectId(objectId),contentType);
            attachementVOList.add(imageAttachementVO);
        }
        if (attachementVOList.size() > 0) {
            return DtoUtil.returnSuccess("查询成功", attachementVOList);
        } else {
            return DtoUtil.returnFail("未查询到记录", "10001");
        }
    }
}
